﻿using System;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using TestMatrix.Model;
using TestMatrix.Phone.Resources;
using Windows.Storage;
using Microsoft.WindowsAzure.MobileServices;
using TestMatrix.DataModel;
using TestMatrix.BLController;
using System.Collections.Generic;

namespace TestMatrix.Phone
{
    public partial class App : Application
    {

        private IMobileServiceTable<ETLHistoryAzure> etlHistoryTable = App.MobileService.GetTable<ETLHistoryAzure>();

        private IMobileServiceTable<BugListAzure> bugListAzureTable = App.MobileService.GetTable<BugListAzure>();
       
        private IMobileServiceTable<NumOfCreatedTCAzure> NumOfCreatedTCAzureTable = App.MobileService.GetTable<NumOfCreatedTCAzure>();

        private IMobileServiceTable<TestAutomationAzure> TestAutomationAzureTable = App.MobileService.GetTable<TestAutomationAzure>();

        private IMobileServiceTable<NumOfExecutedTCAzure> NumOfExecutedTCAzureTable = App.MobileService.GetTable<NumOfExecutedTCAzure>();

        private IMobileServiceTable<ReleaseInfoAzure> ReleaseInfoAzureTable = App.MobileService.GetTable<ReleaseInfoAzure>();

        private IMobileServiceTable<ReleaseDetailInfoAzure> ReleaseDetailInfoAzureTable = App.MobileService.GetTable<ReleaseDetailInfoAzure>();

        private IMobileServiceTable<TestCaseInCIAzure> TestCaseInCIAzureTable = App.MobileService.GetTable<TestCaseInCIAzure>();

        private IMobileServiceTable<GlobalTestCasePassRateAzure> GlobalTestCasePassRateAzureAzureTable = App.MobileService.GetTable<GlobalTestCasePassRateAzure>();

        private IMobileServiceTable<GlobalTestCaseAutomationAzure> GlobalTestCaseAutomationAzureTable = App.MobileService.GetTable<GlobalTestCaseAutomationAzure>();

        private IMobileServiceTable<GlobalDREAzure> GlobalDREAzureAzureTable = App.MobileService.GetTable<GlobalDREAzure>();

        private async void ExtractDataFromAzure()
        {
            #region refresh BugList from Azure

            //truncate table tblBuglist
            ChartController.DeleteAllBugs();

            try
            {
                int takeCount = 900;
                int skipCount = 0;

                while (1 == 1)
                {
                    IMobileServiceTableQuery<BugListAzure> query = bugListAzureTable.Skip(skipCount).Take(takeCount);
                    List<BugListAzure> lstTmp = await query.ToListAsync();

                    List<tblBugList> lstTrg = new List<tblBugList>();
                    foreach (BugListAzure item in lstTmp)
                    {
                        tblBugList bug = new tblBugList();
                        bug.ID = item.Id;
                        bug.ItemID = item.ItemID;
                        bug.ProjectName = item.ProjectName;
                        bug.AssignedTo = item.AssignedTo;
                        bug.State = item.State;
                        bug.Severity = item.Severity;
                        bug.FoundInEnvironment = item.FoundInEnvironment;
                        bug.CreatedDate = item.CreatedDate;
                        bug.ResolvedDate = item.ResolvedDate;
                        bug.ClosedDate = item.ClosedDate;
                        bug.ProjectFriendName = item.ProjectFriendName;
                        bug.BugType = item.BugType;
                        bug.CreatedBy = item.CreatedBy;
                        bug.ResolvedBy = item.ResolvedBy;
                        lstTrg.Add(bug);
                    }
                    ChartController.InsertAllBugs(lstTrg);

                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }

            #endregion

            #region refresh NumOfCreatedTC from Azure

            //truncate table NumOfCreatedTC
            ChartController.DeleteAllTblNumOfCreatedTC();

            try
            {
                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<NumOfCreatedTCAzure> query = NumOfCreatedTCAzureTable.Skip(skipCount).Take(takeCount);
                    List<NumOfCreatedTCAzure> lstTmp = await query.ToListAsync();

                    List<tblNumOfCreatedTC> lstTrg = new List<tblNumOfCreatedTC>();
                    foreach (NumOfCreatedTCAzure item in lstTmp)
                    {
                        tblNumOfCreatedTC tc = new tblNumOfCreatedTC();
                        tc.ID = item.Id;
                        tc.Application = item.Application;
                        tc.CreatedDate = item.CreatedDate;
                        tc.NumCreatedTC = item.NumCreatedTC;
                        lstTrg.Add(tc);
                    }

                    ChartController.InsertAllTblNumOfCreatedTC(lstTrg);


                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh TestAutomation from Azure

            //truncate table TestAutomation
            ChartController.DeleteAllTblTestAutomation();

            try
            {
                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<TestAutomationAzure> query = TestAutomationAzureTable.Skip(skipCount).Take(takeCount);
                    List<TestAutomationAzure> lstTmp = await query.ToListAsync();

                    List<tblTestAutomation> lstTrg = new List<tblTestAutomation>();
                    foreach (TestAutomationAzure item in lstTmp)
                    {
                        tblTestAutomation t = new tblTestAutomation();
                        t.ID = item.Id;
                        t.Application = item.Application;
                        t.CreatedDate = item.CreatedDate;
                        t.TotalTestCases = item.TotalTestCases;
                        t.Automatable = item.Automatable;
                        t.CannotAutomated = item.CannotAutomated;
                        t.AutomatableNotReady = item.AutomatableNotReady;
                        t.AlreadyAutomated = item.AlreadyAutomated;
                        t.Gap = item.Gap;
                        t.RateAutomatable = item.RateAutomatable;
                        t.RateAlreadyAutomated = item.RateAlreadyAutomated;
                        t.LinesOfAutomationCode = item.LinesOfAutomationCode;
                        lstTrg.Add(t);
                    }
                    ChartController.InsertAllTblTestAutomation(lstTrg);

                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh NumOfExecutedTC from Azure

            //truncate table NumOfExecutedTC
            ChartController.DeleteAlltblNumOfExecutedTC();

            try
            {
                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<NumOfExecutedTCAzure> query = NumOfExecutedTCAzureTable.Skip(skipCount).Take(takeCount);
                    List<NumOfExecutedTCAzure> lstTmp = await query.ToListAsync();

                    List<tblNumOfExecutedTC> lstTrg = new List<tblNumOfExecutedTC>();
                    foreach (NumOfExecutedTCAzure item in lstTmp)
                    {
                        tblNumOfExecutedTC t = new tblNumOfExecutedTC();
                        t.ID = item.Id;
                        t.Application = item.Application;
                        t.ExecutedStartDt = item.ExecutedStartDt;
                        t.NumExecutedTC = item.NumExecutedTC;
                        t.NumPassed = item.NumPassed;
                        t.NumFailed = item.NumFailed;
                        lstTrg.Add(t);
                    }

                    ChartController.InsertAlltblNumOfExecutedTC(lstTrg);
                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }

            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh ReleaseInfoAzure from Azure

            //truncate table tblReleaseInfo
            ChartController.DeleteAlltblReleaseInfo();

            try
            {

                int takeCount = 900;
                int skipCount = 0;

                while (1 == 1)
                {
                    IMobileServiceTableQuery<ReleaseInfoAzure> query = ReleaseInfoAzureTable.Skip(skipCount).Take(takeCount);
                    List<ReleaseInfoAzure> lstTmp = await query.ToListAsync();

                    List<tblReleaseInfo> lstTrg = new List<tblReleaseInfo>();
                    foreach (ReleaseInfoAzure item in lstTmp)
                    {
                        tblReleaseInfo t = new tblReleaseInfo();
                        t.ID = item.Id;
                        t.EBIProjectName = item.EBIProjectName;
                        t.YYYYMM = item.YYYYMM;
                        t.ReleaseCnt = item.ReleaseCnt;
                        t.ReleaseTimes = item.ReleaseTimes;
                        t.TestCaseCnt = item.TestCaseCnt;
                        t.ChangeSetCnt = item.ChangeSetCnt;
                        t.FixedBug = item.FixedBug;
                        t.ChangeRequest = item.ChangeRequest;
                        t.Feature = item.Feature;
                        t.Issue = item.Issue;
                        t.Task = item.Task;
                        t.UserStory = item.UserStory;
                        lstTrg.Add(t);
                    }
                    ChartController.InsertAlltblReleaseInfo(lstTrg);

                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh ReleaseDetailInfoAzure from Azure

            //truncate table tblReleaseDetailInfo
            ChartController.DeleteAlltblReleaseDetailInfo();

            try
            {

                int takeCount = 900;
                int skipCount = 0;

                while (1 == 1)
                {
                    IMobileServiceTableQuery<ReleaseDetailInfoAzure> query = ReleaseDetailInfoAzureTable.Skip(skipCount).Take(takeCount);
                    List<ReleaseDetailInfoAzure> lstTmp = await query.ToListAsync();

                    List<tblReleaseDetailInfo> lstTrg = new List<tblReleaseDetailInfo>();
                    foreach (ReleaseDetailInfoAzure item in lstTmp)
                    {
                        tblReleaseDetailInfo t = new tblReleaseDetailInfo();
                        t.ID = item.Id;
                        t.EBIProjectName = item.EBIProjectName;
                        t.YYYYMMDD = item.YYYYMMDD;
                        t.ReleaseCnt = item.ReleaseCnt;
                        t.ReleaseTimes = item.ReleaseTimes;
                        t.TestCaseCnt = item.TestCaseCnt;
                        t.ChangeSetCnt = item.ChangeSetCnt;
                        t.FixedBug = item.FixedBug;
                        t.ChangeRequest = item.ChangeRequest;
                        t.Feature = item.Feature;
                        t.Issue = item.Issue;
                        t.Task = item.Task;
                        t.UserStory = item.UserStory;
                        lstTrg.Add(t);
                    }
                    ChartController.InsertAlltblReleaseDetailInfo(lstTrg);

                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh TestCaseInCIAzure from Azure

            //truncate table TestCaseInCIAzure
            ChartController.DeleteAlltblTestCaseInCI();

            try
            {

                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<TestCaseInCIAzure> query = TestCaseInCIAzureTable.Skip(skipCount).Take(takeCount);
                    List<TestCaseInCIAzure> lstTmp = await query.ToListAsync();

                    List<tblTestCaseInCI> lstTrg = new List<tblTestCaseInCI>();

                    foreach (TestCaseInCIAzure item in lstTmp)
                    {
                        tblTestCaseInCI t = new tblTestCaseInCI();
                        t.ID = item.Id;
                        t.EBIProjectName = item.EBIProjectName;
                        t.ReleasedTestCaseCnt = item.ReleasedTestCaseCnt;
                        t.TestCaseInCI = item.TestCaseInCI;
                        t.TestCase_Auto_CI = item.TestCase_Auto_CI;
                        t.TestCase_Manual_CI = item.TestCase_Manual_CI;
                        t.UTCase_CI = item.UTCase_CI;
                        lstTrg.Add(t);
                    }

                    ChartController.InsertAlltblTestCaseInCI(lstTrg);
                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh tblGlobalTestCasePassRate from Azure

            //truncate table GlobalTestCasePassRateAzure
            ChartController.DeleteAlltblGolbalTestCasePassRate();

            try
            {
                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<GlobalTestCasePassRateAzure> query = GlobalTestCasePassRateAzureAzureTable.Skip(skipCount).Take(takeCount);
                    List<GlobalTestCasePassRateAzure> lstTmp = await query.ToListAsync();

                    List<tblGlobalTestCasePassRate> lstTrg = new List<tblGlobalTestCasePassRate>();
                    foreach (GlobalTestCasePassRateAzure item in lstTmp)
                    {
                        tblGlobalTestCasePassRate t = new tblGlobalTestCasePassRate();
                        t.ID = item.Id;
                        t.Financialyear = item.Financialyear;
                        t.ProjectName = item.ProjectName;
                        t.PlanName = item.PlanName;
                        t.Passed = item.Passed;
                        t.Failed = item.Failed;
                        t.NotExecuted = item.NotExecuted;
                        t.Total = item.Total;
                        t.PassPercent = item.PassPercent;
                        lstTrg.Add(t);
                    }
                    ChartController.InsertAlltblGolbalTestCasePassRate(lstTrg);

                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh tblGlobalTestCaseAutomation from Azure

            //truncate table GlobalTestCaseAutomationAzure
            ChartController.DeleteAlltblGlobalTestCaseAutomation();

            try
            {
                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<GlobalTestCaseAutomationAzure> query = GlobalTestCaseAutomationAzureTable.Skip(skipCount).Take(takeCount);
                    List<GlobalTestCaseAutomationAzure> lstTmp = await query.ToListAsync();

                    List<tblGlobalTestCaseAutomation> lstTrg = new List<tblGlobalTestCaseAutomation>();
                    foreach (GlobalTestCaseAutomationAzure item in lstTmp)
                    {
                        tblGlobalTestCaseAutomation t = new tblGlobalTestCaseAutomation();
                        t.ID = item.Id;
                        t.Financialyear = item.Financialyear;
                        t.Project = item.Project;
                        t.Automated = item.Automated;
                        t.HaveAutomationValue = item.HaveAutomationValue;
                        t.NotAutomationValue = item.NotAutomationValue;
                        t.AutomatedOfTotal = item.AutomatedOfTotal;
                        t.AutomatedOfAutomatable = item.AutomatedOfAutomatable;
                        lstTrg.Add(t);
                    }

                    ChartController.InsertAlltblGlobalTestCaseAutomation(lstTrg);
                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion

            #region refresh tblGlobalDRE from Azure

            //truncate table GlobalDREAzure
            ChartController.DeleteAlltblGlobalDRE();

            try
            {
                int takeCount = 900;
                int skipCount = 0;
                while (1 == 1)
                {
                    IMobileServiceTableQuery<GlobalDREAzure> query = GlobalDREAzureAzureTable.Skip(skipCount).Take(takeCount);
                    List<GlobalDREAzure> lstTmp = await query.ToListAsync();

                    List<tblGlobalDRE> lstTrg = new List<tblGlobalDRE>();

                    foreach (GlobalDREAzure item in lstTmp)
                    {
                        tblGlobalDRE t = new tblGlobalDRE();
                        t.ID = item.Id;
                        t.Financialyear = item.Financialyear;
                        t.Project = item.Project;
                        t.SITBugs = item.SITBugs;
                        t.ProductionUATBUGS = item.ProductionUATBUGS;
                        t.OtherBugs = item.OtherBugs;
                        t.DRE = item.DRE;
                        lstTrg.Add(t);
                    }

                    ChartController.InsertAlltblGlobalDRE(lstTrg);

                    if (lstTmp.Count < takeCount)
                    {
                        break;
                    }

                    skipCount = skipCount + takeCount;
                }
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                MessageBox.Show(ex.Message, "Error loading items", MessageBoxButton.OK);
            }
            #endregion
        }

        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public static PhoneApplicationFrame RootFrame { get; private set; }

        //old key
        //public static MobileServiceClient MobileService = new MobileServiceClient(
        //    "https://testmetrics.azure-mobile.net/", "iaPuUksFgrplUtomnFHFoaDcmrPUJZ69"
        //   );

        //new key
        public static MobileServiceClient MobileService = new MobileServiceClient(
         "https://istestmetrics.azure-mobile.net/",
        "rgBOcetFACxqNlippvSXOIdOSjNvIK23"
        );

        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard XAML initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Language display initialization
            InitializeLanguage();

            // Show graphics profiling information while debugging.
            if (Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are handed off to GPU with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Prevent the screen from turning off while under the debugger by disabling
                // the application's idle detection.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private async void Application_Launching(object sender, LaunchingEventArgs e)
        {
            //// Copy file from installation folder to local folder.
            //// Obtain the virtual store for the application.
            //IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

            //// Create a stream for the file in the installation folder.
            //using (Stream input = Application.GetResourceStream(new Uri(ConstantDefinition.DB_FILE_NAME, UriKind.Relative)).Stream)
            //{
            //    // Create a stream for the new file in the local folder.
            //    using (IsolatedStorageFileStream output = iso.CreateFile(ConstantDefinition.DB_PATH))
            //    {
            //        // Initialize the buffer.
            //        byte[] readBuffer = new byte[4096];
            //        int bytesRead = -1;

            //        // Copy the file from the installation folder to the local folder. 
            //        while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
            //        {
            //            output.Write(readBuffer, 0, bytesRead);
            //        }
            //    }
            //}

            StorageFile dbFile = null;
            try
            {
                // Try to get the 
                dbFile = await StorageFile.GetFileFromPathAsync(ConstantDefinition.DB_PATH);
            }
            catch (FileNotFoundException)
            {
                if (dbFile == null)
                {
                    // Copy file from installation folder to local folder.
                    // Obtain the virtual store for the application.
                    IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();

                    // Create a stream for the file in the installation folder.
                    using (Stream input = Application.GetResourceStream(new Uri(ConstantDefinition.DB_FILE_NAME, UriKind.Relative)).Stream)
                    {
                        // Create a stream for the new file in the local folder.
                        using (IsolatedStorageFileStream output = iso.CreateFile(ConstantDefinition.DB_PATH))
                        {
                            // Initialize the buffer.
                            byte[] readBuffer = new byte[4096];
                            int bytesRead = -1;

                            // Copy the file from the installation folder to the local folder. 
                            while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
                            {
                                output.Write(readBuffer, 0, bytesRead);
                            }
                        }
                    }
                }
            }

            ExtractDataFromAzure();

        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Handle reset requests for clearing the backstack
            RootFrame.Navigated += CheckForResetNavigation;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        private void CheckForResetNavigation(object sender, NavigationEventArgs e)
        {
            // If the app has received a 'reset' navigation, then we need to check
            // on the next navigation to see if the page stack should be reset
            if (e.NavigationMode == NavigationMode.Reset)
                RootFrame.Navigated += ClearBackStackAfterReset;
        }

        private void ClearBackStackAfterReset(object sender, NavigationEventArgs e)
        {
            // Unregister the event so it doesn't get called again
            RootFrame.Navigated -= ClearBackStackAfterReset;

            // Only clear the stack for 'new' (forward) and 'refresh' navigations
            if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
                return;

            // For UI consistency, clear the entire page stack
            while (RootFrame.RemoveBackEntry() != null)
            {
                ; // do nothing
            }
        }

        #endregion

        // Initialize the app's font and flow direction as defined in its localized resource strings.
        //
        // To ensure that the font of your application is aligned with its supported languages and that the
        // FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
        // and ResourceFlowDirection should be initialized in each resx file to match these values with that
        // file's culture. For example:
        //
        // AppResources.es-ES.resx
        //    ResourceLanguage's value should be "es-ES"
        //    ResourceFlowDirection's value should be "LeftToRight"
        //
        // AppResources.ar-SA.resx
        //     ResourceLanguage's value should be "ar-SA"
        //     ResourceFlowDirection's value should be "RightToLeft"
        //
        // For more info on localizing Windows Phone apps see http://go.microsoft.com/fwlink/?LinkId=262072.
        //
        private void InitializeLanguage()
        {
            try
            {
                // Set the font to match the display language defined by the
                // ResourceLanguage resource string for each supported language.
                //
                // Fall back to the font of the neutral language if the Display
                // language of the phone is not supported.
                //
                // If a compiler error is hit then ResourceLanguage is missing from
                // the resource file.
                RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);

                // Set the FlowDirection of all elements under the root frame based
                // on the ResourceFlowDirection resource string for each
                // supported language.
                //
                // If a compiler error is hit then ResourceFlowDirection is missing from
                // the resource file.
                FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
                RootFrame.FlowDirection = flow;
            }
            catch
            {
                // If an exception is caught here it is most likely due to either
                // ResourceLangauge not being correctly set to a supported language
                // code or ResourceFlowDirection is set to a value other than LeftToRight
                // or RightToLeft.

                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                throw;
            }
        }
    }
}